/**
 * 工单投诉统计
 */
angular.module('inspinia', ['infinity.angular-chosen']).controller('workCensusQueryCtrl', function ($scope, $http, $state, i18nService, $document, $timeout, SweetAlert) {
  //数据源
  i18nService.setCurrentLang('zh-cn');
  $scope.paginationOptions = {pageNo: 1, pageSize: 10};

  //投诉总量统计
  $scope.countTeam = 0;
  $scope.cancelTeamTable = function () {
    $scope.infoTeam = {
      dateStrBegin: moment(new Date().getTime() - 30 * 24 * 60 * 60 * 1000).format('YYYY-MM-DD'),
      dateStrEnd: moment(new Date().getTime()).format('YYYY-MM-DD')
    };
  }
  $scope.cancelTeamTable();

  $scope.columnDefsTeam = [
    {
      field: 'dayDate',
      displayName: '统计日期',
      width: 220,
      pinnable: false,
      sortable: false,
      cellFilter: 'date:"yyyy-MM-dd"'
    },
    {field: 'count', displayName: '合计', width: 180, pinnable: false, sortable: false},
    {field: 'agentCount', displayName: '涉及服务商', width: 180, pinnable: false, sortable: false},
    {field: 'linkRelativeRatio', displayName: '环比(较上月)', width: 180, pinnable: false, sortable: false}
  ];
  $scope.myGridTeam = {
    paginationPageSize: 10,                  //分页数量
    paginationPageSizes: [10, 20, 50, 100],	//切换每页记录数
    useExternalPagination: true,		  //开启拓展名
    enableHorizontalScrollbar: true,        //横向滚动条
    enableVerticalScrollbar: true,  		//纵向滚动条
    columnDefs: $scope.columnDefsTeam,
    onRegisterApi: function (gridApi) {
      $scope.gridApiTeam = gridApi;
      $scope.gridApiTeam.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
        $scope.paginationOptions.pageNo = newPage;
        $scope.paginationOptions.pageSize = pageSize;
        $scope.teamQuery(false);
      });
    }
  };

  $scope.initTable = function (teamAllList, columns) {
    $scope.deleteKey(columns);
    //去除表上字段
    if (teamAllList != null && teamAllList.length > 0) {
      for (var i = teamAllList.length - 1; i >= 0; i--) {
        var item = teamAllList[i];//team123;
        var key = "team" + item.teamId.replace("-", "_");
        var keyName = "投诉次数(" + item.teamName + ")";
        if ($scope.queryKey(columns, key)) {
          columns.splice(1, 0, {field: key, displayName: keyName, width: 220, pinnable: false, sortable: false});
        }
      }
    }
  }
  //还原表格
  $scope.queryKey = function (list, key) {
    if (list != null && list.length > 0) {
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (key == item.field) {
          return false;
        }
      }
    }
    return true;
  }
  //还原表格
  $scope.deleteKey = function (list) {
    if (list != null && list.length > 0) {
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        var key = item.field;
        //如果已team字段为首的
        if (key.indexOf("team") == 0) {
          list.splice(i, 1);
          i--;
        }
      }
    }
  }

  $scope.getCountTeamList = function () {
    $http.get('workCensus/getCountTeamList').success(function (data) {
      if (data.status) {
        $scope.initTable(data.teamAllList, $scope.columnDefsTeam);
      }
    });
  }
  $scope.getCountTeamList();

  /**
   * 校验team查询条件
   */
  $scope.teamQueryCheck = function () {
    if ($scope.infoTeam.dateStrBegin == null || $scope.infoTeam.dateStrBegin == ""
      || $scope.infoTeam.dateStrEnd == null || $scope.infoTeam.dateStrEnd == "") {
      $scope.notice("统计日期不能为空!");
      return false;
    } else {
      var stime = new Date($scope.infoTeam.dateStrBegin).getTime();
      var etime = new Date($scope.infoTeam.dateStrEnd).getTime();
      if ((etime - stime) > (180 * 24 * 60 * 60 * 1000)) {
        $scope.notice("统计日期范围不能超过180天");
        return false;
      }
    }
    return true;
  }


  $scope.loadImg = false;
  $scope.teamQuery = function (initSta) {
    //校验条件
    if (!$scope.teamQueryCheck()) {
      return;
    }

    if ($scope.loadImg) {
      return;
    }
    $scope.loadImg = true;
    //查询列表
    var data = {
      info: angular.toJson($scope.infoTeam),
      pageNo: $scope.paginationOptions.pageNo,
      pageSize: $scope.paginationOptions.pageSize
    };
    var postCfg = {
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      transformRequest: function (data) {
        return $.param(data);
      }
    };
    $http.post("workCensus/countTeamWork", data, postCfg)
      .success(function (data) {
        if (data.status) {
          $scope.myGridTeam.data = data.list;
          $scope.initTable(data.teamAllList, $scope.columnDefsTeam);
        } else {
          $scope.notice(data.msg);
        }
        $scope.loadImg = false;
      })
      .error(function (data) {
        $scope.notice(data.msg);
        $scope.loadImg = false;
      });

    if (initSta) {
      //查询统计
      var data = {info: angular.toJson($scope.infoTeam)};
      var postCfg = {
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function (data) {
          return $.param(data);
        }
      };
      $http.post("workCensus/countTeamWorkCount", data, postCfg)
        .success(function (data) {
          if (data.status) {
            var countInfo = data.countInfo;
            $scope.myGridTeam.totalItems = countInfo.count == null ? 0 : countInfo.count;
            $scope.countTeam = countInfo.countNum == null ? 0 : countInfo.countNum;
          } else {
            $scope.notice(data.msg);
          }
        });
    }
  };

  // 导出
  $scope.exportTeamWork = function () {
    //校验条件
    if (!$scope.teamQueryCheck()) {
      return;
    }
    SweetAlert.swal({
        title: "确认导出？",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
      },
      function (isConfirm) {
        if (isConfirm) {
          $scope.exportInfoClick("workCensus/exportTeamWork", {"info": angular.toJson($scope.infoTeam)});
        }
      });
  };

  //--------------------------------


  //下级代理商被投诉排名
  $scope.countAgent = 0;
  $scope.paginationOptionsAgent = {pageNo: 1, pageSize: 10};

  $scope.cancelAgentTable = function () {
    $scope.infoAgent = {
      dateStrBegin: moment(new Date().getTime()).format('YYYY-MM'),
      dateStrEnd: moment(new Date().getTime()).format('YYYY-MM')
    };
  }
  $scope.cancelAgentTable();

  $scope.columnDefsAgent = [
    {field: 'rank', displayName: '排序', width: 100, pinnable: false, sortable: false},
    {
      field: 'createTime',
      displayName: '统计月份',
      width: 120,
      pinnable: false,
      sortable: false,
      cellFilter: 'date:"yyyy年MM月"'
    },
    {field: 'agentName', displayName: '所属代理商名称', width: 180, pinnable: false, sortable: false},
    {field: 'agentNo', displayName: '所属代理商编号', width: 120, pinnable: false, sortable: false},
    {field: 'agentLevel', displayName: '代理商等级', width: 120, pinnable: false, sortable: false},
    {field: 'oneAgentName', displayName: '一级代理商名称', width: 120, pinnable: false, sortable: false},
    {field: 'oneAgentNo', displayName: '一级代理商编号', width: 120, pinnable: false, sortable: false},
    {field: 'count', displayName: '投诉商户(总计)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult2', displayName: '投诉商户(已退款)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult3', displayName: '投诉商户(协商一致)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult4', displayName: '投诉商户(未处理)', width: 180, pinnable: false, sortable: false},
    {field: 'oneAgentSaleName', displayName: '对接经理', width: 180, pinnable: false, sortable: false}
  ];
  $scope.myGridAgent = {
    paginationPageSize: 10,                  //分页数量
    paginationPageSizes: [10, 20, 50, 100],	//切换每页记录数
    useExternalPagination: true,		  //开启拓展名
    enableHorizontalScrollbar: true,        //横向滚动条
    enableVerticalScrollbar: true,  		//纵向滚动条
    columnDefs: $scope.columnDefsAgent,
    onRegisterApi: function (gridApi) {
      $scope.gridApiAgent = gridApi;
      $scope.gridApiAgent.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
        $scope.paginationOptionsAgent.pageNo = newPage;
        $scope.paginationOptionsAgent.pageSize = pageSize;
        $scope.agentQuery(false);
      });
    }
  };

  /**
   * 校验agent查询条件
   */
  $scope.agentQueryCheck = function () {
    if ($scope.infoAgent.dateStrBegin == null || $scope.infoAgent.dateStrBegin == ""
      || $scope.infoAgent.dateStrEnd == null || $scope.infoAgent.dateStrEnd == "") {
      $scope.notice("月份不能为空!");
      return false;
    } else {
      var time1 = new Date($scope.infoAgent.dateStrBegin);
      var time2 = new Date($scope.infoAgent.dateStrEnd);
      var diffyear = time2.getFullYear() - time1.getFullYear();
      var diffmonth = diffyear * 12 + time2.getMonth() - time1.getMonth();
      if (diffmonth >= 6) {
        $scope.notice("月份范围不能超过6个月");
        return false;
      }
    }
    return true;
  }

  $scope.loadImgAgent = false;
  $scope.agentQuery = function (initSta) {
    //校验
    if (!$scope.agentQueryCheck()) {
      return;
    }

    if ($scope.loadImgAgent) {
      return;
    }
    $scope.loadImgAgent = true;
    //查询列表
    var data = {
      info: angular.toJson($scope.infoAgent),
      pageNo: $scope.paginationOptionsAgent.pageNo,
      pageSize: $scope.paginationOptionsAgent.pageSize
    };
    var postCfg = {
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      transformRequest: function (data) {
        return $.param(data);
      }
    };
    $http.post("workCensus/countAgentWork", data, postCfg)
      .success(function (data) {
        if (data.status) {
          $scope.myGridAgent.data = data.list;
        } else {
          $scope.notice(data.msg);
        }
        $scope.loadImgAgent = false;
      })
      .error(function (data) {
        $scope.notice(data.msg);
        $scope.loadImgAgent = false;
      });

    if (initSta) {
      //查询统计
      var data = {info: angular.toJson($scope.infoAgent)};
      var postCfg = {
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function (data) {
          return $.param(data);
        }
      };
      $http.post("workCensus/countAgentWorkCount", data, postCfg)
        .success(function (data) {
          if (data.status) {
            var countInfo = data.countInfo;
            $scope.myGridAgent.totalItems = countInfo.count == null ? 0 : countInfo.count;
            $scope.countAgent = countInfo.countNum == null ? 0 : countInfo.countNum;
          } else {
            $scope.notice(data.msg);
          }
        });
    }
  };


  // 导出
  $scope.exportAgentWork = function () {
    //校验
    if (!$scope.agentQueryCheck()) {
      return;
    }
    SweetAlert.swal({
        title: "确认导出？",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
      },
      function (isConfirm) {
        if (isConfirm) {
          $scope.exportInfoClick("workCensus/exportAgentWork", {"info": angular.toJson($scope.infoAgent)});
        }
      });
  };


  //代理商
  $scope.agentList = [{value: "", text: "全部"}];

  $http.post("agentInfo/selectAllInfo")
    .success(function (msg) {
      //响应成功
      for (var i = 0; i < msg.length; i++) {
        $scope.agentList.push({value: msg[i].agentNo, text: msg[i].agentNo + " " + msg[i].agentName});
      }
    });

  //异步获取直属代理商
  var oldValue = "";
  var timeout = "";
  $scope.getAgentList = function (value) {
    var agentt = [];
    var newValue = value;
    if (newValue != oldValue) {
      if (timeout) $timeout.cancel(timeout);
      timeout = $timeout(
        function () {
          $http.post('agentInfo/selectAllInfo', 'item=' + value,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then(function (response) {
              if (response.data.length == 0) {
                agentt.push({value: "", text: "全部"});
              } else {
                agentt.push({value: "", text: "全部"});
                for (var i = 0; i < response.data.length; i++) {
                  agentt.push({
                    value: response.data[i].agentNo,
                    text: response.data[i].agentNo + " " + response.data[i].agentName
                  });
                }
              }
              $scope.agentList = agentt;
              oldValue = value;
            });
        }, 800);
    }
  };


  //销售
  $scope.saleList = [{value: "", text: "全部"}];

  $http.post("agentInfo/selectAllSale")
    .success(function (msg) {
      //响应成功
      for (var i = 0; i < msg.length; i++) {
        $scope.saleList.push({value: msg[i].realName, text: msg[i].realName});
      }
    });


  var oldValue4 = "";
  var timeout4 = "";
  $scope.getSaleList = function (value) {
    var agentt = [];
    var newValue = value;
    if (newValue != oldValue4) {
      if (timeout) $timeout.cancel(timeout4);
      timeout4 = $timeout(
        function () {
          $http.post('agentInfo/selectAllSale', 'item=' + value,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then(function (response) {
              if (response.data.length == 0) {
                agentt.push({value: "", text: "全部"});
              } else {
                agentt.push({value: "", text: "全部"});
                for (var i = 0; i < response.data.length; i++) {
                  agentt.push({value: response.data[i].realName, text: response.data[i].realName});
                }
              }
              $scope.saleList = agentt;
              oldValue4 = value;
            });
        }, 800);
    }
  };


  //--------------------------------------------------------------------------------------------------------------------------------


  //一级代理商被投诉排名
  $scope.countAgent2 = 0;
  $scope.paginationOptionsAgent2 = {pageNo: 1, pageSize: 10};

  $scope.cancelAgentTable2 = function () {
    $scope.infoAgent2 = {
      dateStrBegin: moment(new Date().getTime()).format('YYYY-MM'),
      dateStrEnd: moment(new Date().getTime()).format('YYYY-MM')
    };
  }
  $scope.cancelAgentTable2();

  $scope.columnDefsAgent2 = [
    {field: 'rank', displayName: '排序', width: 100, pinnable: false, sortable: false},
    {
      field: 'createTime',
      displayName: '统计月份',
      width: 120,
      pinnable: false,
      sortable: false,
      cellFilter: 'date:"yyyy年MM月"'
    },
    {field: 'oneAgentName', displayName: '代理商名称', width: 180, pinnable: false, sortable: false},
    {field: 'oneAgentNo', displayName: '代理商编号', width: 120, pinnable: false, sortable: false},
    {field: 'count', displayName: '投诉商户(总计)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult2', displayName: '投诉商户(已退款)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult3', displayName: '投诉商户(协商一致)', width: 180, pinnable: false, sortable: false},
    {field: 'dealResult4', displayName: '投诉商户(未处理)', width: 180, pinnable: false, sortable: false},
    {field: 'countPart', displayName: '占比', width: 180, pinnable: false, sortable: false},
    {field: 'oneAgentSaleName', displayName: '对接经理', width: 180, pinnable: false, sortable: false}
  ];
  $scope.myGridAgent2 = {
    paginationPageSize: 10,                  //分页数量
    paginationPageSizes: [10, 20, 50, 100],	//切换每页记录数
    useExternalPagination: true,		  //开启拓展名
    enableHorizontalScrollbar: true,        //横向滚动条
    enableVerticalScrollbar: true,  		//纵向滚动条
    columnDefs: $scope.columnDefsAgent2,
    onRegisterApi: function (gridApi) {
      $scope.gridApiAgent = gridApi;
      $scope.gridApiAgent.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
        $scope.paginationOptionsAgent2.pageNo = newPage;
        $scope.paginationOptionsAgent2.pageSize = pageSize;
        $scope.agentQuery2(false);
      });
    }
  };

  /**
   * 校验agent查询条件
   */
  $scope.agentQueryCheck2 = function () {
    if ($scope.infoAgent2.dateStrBegin == null || $scope.infoAgent2.dateStrBegin == ""
      || $scope.infoAgent2.dateStrEnd == null || $scope.infoAgent2.dateStrEnd == "") {
      $scope.notice("月份不能为空!");
      return false;
    } else {
      var time1 = new Date($scope.infoAgent2.dateStrBegin);
      var time2 = new Date($scope.infoAgent2.dateStrEnd);
      var diffyear = time2.getFullYear() - time1.getFullYear();
      var diffmonth = diffyear * 12 + time2.getMonth() - time1.getMonth();
      if (diffmonth >= 6) {
        $scope.notice("月份范围不能超过6个月");
        return false;
      }
    }
    return true;
  }

  $scope.loadImgAgent2 = false;
  $scope.agentQuery2 = function (initSta) {
    //校验
    if (!$scope.agentQueryCheck2()) {
      return;
    }

    if ($scope.loadImgAgent2) {
      return;
    }
    $scope.loadImgAgent2 = true;
    //查询列表
    var data = {
      info: angular.toJson($scope.infoAgent2),
      pageNo: $scope.paginationOptionsAgent2.pageNo,
      pageSize: $scope.paginationOptionsAgent2.pageSize
    };
    var postCfg = {
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      transformRequest: function (data) {
        return $.param(data);
      }
    };
    $http.post("workCensus/countAgentWork2", data, postCfg)
      .success(function (data) {
        if (data.status) {
          $scope.myGridAgent2.data = data.list;
        } else {
          $scope.notice(data.msg);
        }
        $scope.loadImgAgent2 = false;
      })
      .error(function (data) {
        $scope.notice(data.msg);
        $scope.loadImgAgent2 = false;
      });

    if (initSta) {
      //查询统计
      var data = {info: angular.toJson($scope.infoAgent2)};
      var postCfg = {
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        transformRequest: function (data) {
          return $.param(data);
        }
      };
      $http.post("workCensus/countAgentWorkCount2", data, postCfg)
        .success(function (data) {
          if (data.status) {
            var countInfo = data.countInfo;
            $scope.myGridAgent2.totalItems = countInfo.count == null ? 0 : countInfo.count;
            $scope.countAgent2 = countInfo.countNum == null ? 0 : countInfo.countNum;
          } else {
            $scope.notice(data.msg);
          }
        });
    }
  };


  // 导出
  $scope.exportAgentWork2 = function () {
    //校验
    if (!$scope.agentQueryCheck2()) {
      return;
    }
    SweetAlert.swal({
        title: "确认导出？",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "提交",
        cancelButtonText: "取消",
        closeOnConfirm: true,
        closeOnCancel: true
      },
      function (isConfirm) {
        if (isConfirm) {
          $scope.exportInfoClick("workCensus/exportAgentWork2", {"info": angular.toJson($scope.infoAgent2)});
        }
      });
  };


  //代理商
  $scope.agentList2 = [{value: "", text: "全部"}];

  $http.post("agentInfo/selectAllInfo")
    .success(function (msg) {
      //响应成功
      for (var i = 0; i < msg.length; i++) {
        $scope.agentList2.push({value: msg[i].agentNo, text: msg[i].agentNo + " " + msg[i].agentName});
      }
    });

  //异步获取直属代理商
  var oldValue2 = "";
  var timeout2 = "";
  $scope.getAgentList2 = function (value) {
    var agentt = [];
    var newValue = value;
    if (newValue != oldValue2) {
      if (timeout) $timeout.cancel(timeout2);
      timeout2 = $timeout(
        function () {
          $http.post('agentInfo/selectAllInfo', 'item=' + value,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then(function (response) {
              if (response.data.length == 0) {
                agentt.push({value: "", text: "全部"});
              } else {
                agentt.push({value: "", text: "全部"});
                for (var i = 0; i < response.data.length; i++) {
                  agentt.push({
                    value: response.data[i].agentNo,
                    text: response.data[i].agentNo + " " + response.data[i].agentName
                  });
                }
              }
              $scope.agentList2 = agentt;
              oldValue = value;
            });
        }, 800);
    }
  };


  //销售
  $scope.saleList2 = [{value: "", text: "全部"}];

  $http.post("agentInfo/selectAllSale")
    .success(function (msg) {
      //响应成功
      for (var i = 0; i < msg.length; i++) {
        $scope.saleList2.push({value: msg[i].realName, text: msg[i].realName});
      }
    });


  var oldValue3 = "";
  var timeout3 = "";
  $scope.getSaleList2 = function (value) {
    var agentt = [];
    var newValue = value;
    if (newValue != oldValue3) {
      if (timeout) $timeout.cancel(timeout3);
      timeout3 = $timeout(
        function () {
          $http.post('agentInfo/selectAllSale', 'item=' + value,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then(function (response) {
              if (response.data.length == 0) {
                  agentt.push({value: "", text: "全部"});
              } else {
                  agentt.push({value: "", text: "全部"});
                for (var i = 0; i < response.data.length; i++) {
                    agentt.push({value: response.data[i].realName, text: response.data[i].realName});
                }
              }
              $scope.saleList2 = agentt;
              oldValue3 = value;
            });
        }, 800);
    }
  };


});